package org.example.leetcpde;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Permute
        implements IArray {
    @Test
    void run() {
        int[] nums = parse("[1,1,3]");
        System.out.println(nums);
        List<List<Integer>> permute = permute(nums);
        for (List<Integer> integers : permute) {
            for (Integer n : integers) {
                System.out.print(n);
            }

            System.out.println();
        }
    }

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(new ArrayList<>(), nums, new boolean[nums.length], res);
        return res;
    }

    void dfs(List<Integer> state,
             int[] choices,
             boolean[] selected,
             List<List<Integer>> res) {
        if (state.size() == choices.length) {
            res.add(new ArrayList<>(state));
            return;
        }

        Set<Integer> dup = new HashSet<>();
        for (int i = 0; i < choices.length; i++) {
            if (selected[i]) {
                continue;
            }

            int choice = choices[i];
            if (dup.contains(choice)) {
                continue;
            }

            dup.add(choice);
            selected[i] = true;
            state.add(choice);
            dfs(state, choices, selected, res);
            selected[i] = false;
            state.remove(state.size() - 1);
        }
    }
}
